package com.example.service.conversation.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.common.ResponseVO;
import com.example.common.config.AppConfig;
import com.example.common.constant.ConsoleColors;
import com.example.common.constant.Constants;
import com.example.common.enums.ConversationErrorCode;
import com.example.common.enums.ConversationTypeEnum;
import com.example.common.enums.command.ConversationEventCommand;
import com.example.common.model.ClientInfo;
import com.example.common.model.SyncReq;
import com.example.common.model.SyncResp;
import com.example.common.model.message.MessageReadedContent;
import com.example.pack.conversation.DeleteConversationPack;
import com.example.pack.conversation.UpdateConversationPack;
import com.example.service.conversation.dao.ImConversationSetEntity;
import com.example.service.conversation.dao.mapper.ImConversationSetMapper;
import com.example.service.conversation.model.DeleteConversationReq;
import com.example.service.conversation.model.UpdateConversationReq;
import com.example.service.friendship.dao.ImFriendShipEntity;
import com.example.service.seq.RedisSeq;
import com.example.service.utils.MessageProducer;
import com.example.service.utils.WriteUserSeq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;


@Service
@Slf4j
public class ConversationService {


    @Autowired
    ImConversationSetMapper imConversationSetMapper;

    @Autowired
    MessageProducer messageProducer;

    @Autowired
    AppConfig appConfig;

    @Autowired
    RedisSeq redisSeq;

    @Autowired
    WriteUserSeq writeUserSeq;


    //进行返回会话的id
    public String convertConversationId(Integer type, String fromId, String toId) {
        return type + "_" + fromId + "_" + toId;
    }

    //消息标记已读
    public void messageMarkRead(MessageReadedContent messageReadedContent) {

        //由于可能是群聊消息的已读
        String toId = messageReadedContent.getToId();
        if (messageReadedContent.getConversationType() == ConversationTypeEnum.GROUP.getCode()) {   //表示是群聊的情况下
            toId = messageReadedContent.getGroupId();
        }

        String conversationId = convertConversationId(messageReadedContent.getConversationType(), messageReadedContent.getFromId(), toId);
        QueryWrapper<ImConversationSetEntity> query = new QueryWrapper<>();
        query.eq("conversation_id", conversationId);
        query.eq("app_id", messageReadedContent.getAppId());
        ImConversationSetEntity imConversationSetEntity = imConversationSetMapper.selectOne(query);
        if (imConversationSetEntity == null) {   //如果会话不存在就进行初见会话
            imConversationSetEntity = new ImConversationSetEntity();
            //为会话设置seq
            long seq = redisSeq.doGetSeq(messageReadedContent.getAppId() + ":" + Constants.SeqConstants.Conversation);
            imConversationSetEntity.setConversationId(conversationId);
            BeanUtils.copyProperties(messageReadedContent, imConversationSetEntity);
            imConversationSetEntity.setReadedSequence(messageReadedContent.getMessageSequence());
            imConversationSetEntity.setToId(toId);
            imConversationSetEntity.setSequence(seq);
            imConversationSetMapper.insert(imConversationSetEntity);
            writeUserSeq.writeUserSeq(messageReadedContent.getAppId(),messageReadedContent.getFromId(),Constants.SeqConstants.Conversation,seq);
        } else {   //存在的话就进行修改
            long seq = redisSeq.doGetSeq(messageReadedContent.getAppId() + ":" + Constants.SeqConstants.Conversation);
            imConversationSetEntity.setReadedSequence(messageReadedContent.getMessageSequence());
            imConversationSetEntity.setSequence(seq);
            imConversationSetMapper.readMark(imConversationSetEntity);
            writeUserSeq.writeUserSeq(messageReadedContent.getAppId(),messageReadedContent.getFromId(),Constants.SeqConstants.Conversation,seq);
        }
    }


    //删除会话
    public ResponseVO deleteConversation(DeleteConversationReq req) {

        //置顶 有免打扰
//        QueryWrapper<ImConversationSetEntity> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("conversation_id",req.getConversationId());
//        queryWrapper.eq("app_id",req.getAppId());
//        ImConversationSetEntity imConversationSetEntity = imConversationSetMapper.selectOne(queryWrapper);
//        if(imConversationSetEntity != null){
//            imConversationSetEntity.setIsMute(0);
//            imConversationSetEntity.setIsTop(0);
//            imConversationSetMapper.update(imConversationSetEntity,queryWrapper);
//        }

        if (appConfig.getDeleteConversationSyncMode() == 1) {    //进行判断需不需要进行多端同步
            DeleteConversationPack pack = new DeleteConversationPack();
            pack.setConversationId(req.getConversationId());
            messageProducer.sendToUserExceptClient(req.getFromId(),
                    ConversationEventCommand.CONVERSATION_DELETE,
                    pack, new ClientInfo(req.getAppId(), req.getClientType(),
                            req.getImei()));
        }
        return ResponseVO.successResponse();
    }

    public ResponseVO updateConversation(UpdateConversationReq req) {
        if (req.getIsTop() == null && req.getIsMute() == null) {
            return ResponseVO.errorResponse(ConversationErrorCode.CONVERSATION_UPDATE_PARAM_ERROR);
        }
        QueryWrapper<ImConversationSetEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("conversation_id", req.getConversationId());
        queryWrapper.eq("app_id", req.getAppId());
        ImConversationSetEntity imConversationSetEntity = imConversationSetMapper.selectOne(queryWrapper);
        if (imConversationSetEntity != null) {
            long seq = redisSeq.doGetSeq(req.getAppId() + ":" + Constants.SeqConstants.Conversation);

            if (req.getIsMute() != null) {
                imConversationSetEntity.setIsTop(req.getIsTop());
            }
            if (req.getIsMute() != null) {
                imConversationSetEntity.setIsMute(req.getIsMute());
            }

            imConversationSetEntity.setSequence(seq);      //在更新之前设置seq
            imConversationSetMapper.update(imConversationSetEntity, queryWrapper);
            //这里是使用fromId来表示操作人的 所以fromId 不能为空
            writeUserSeq.writeUserSeq(req.getAppId(),req.getFromId(),Constants.SeqConstants.Conversation,seq);   //更新之后设置到redis中
            UpdateConversationPack pack = new UpdateConversationPack();
            pack.setConversationId(req.getConversationId());
            pack.setIsMute(imConversationSetEntity.getIsMute());
            pack.setIsTop(imConversationSetEntity.getIsTop());
            pack.setSequence(seq);
            pack.setConversationType(imConversationSetEntity.getConversationType());
            messageProducer.sendToUserExceptClient(req.getFromId(),
                    ConversationEventCommand.CONVERSATION_DELETE,
                    pack, new ClientInfo(req.getAppId(), req.getClientType(),
                            req.getImei()));


        }
        return ResponseVO.successResponse();
    }

    public ResponseVO syncConversationSet(SyncReq req) {
        if(req.getMaxLimit()>100){
            req.setMaxLimit(100);                          //进行限制一次不能太多
        }
        SyncResp<ImConversationSetEntity> resp = new SyncResp<>();
        QueryWrapper<ImConversationSetEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("from_id",req.getOperater());
        queryWrapper.gt("sequence",req.getLastSequence());
        queryWrapper.eq("app_id",req.getAppId());
        queryWrapper.last(" limit " + req.getMaxLimit());
        queryWrapper.orderByAsc("sequence");     //这样最大的元素就是最后一个
        List<ImConversationSetEntity> list = imConversationSetMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(list)){
            ImConversationSetEntity maxSeqEntity = list.get(list.size() - 1);    //获取最大的
            resp.setDataList(list);
            //设置最大seq
            Long conversationSetMaxSeq = imConversationSetMapper.geConversationSetMaxSeq(req.getAppId(), req.getOperater());
            resp.setMaxSequence(conversationSetMaxSeq);
            //设置是否拉取完毕
            resp.setCompleted(maxSeqEntity.getSequence()>=conversationSetMaxSeq); //进行判断现在是不是最大了的
            return ResponseVO.successResponse(resp);
        }
        resp.setCompleted(true);
        return ResponseVO.successResponse(resp);
    }
}